package com.example.demo2hw05regist;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.example.demo2hw05regist.MD5.getMD5;

/*
    用于注册用户
 */
@Controller //控制器
@RequestMapping(path="/student")//用户通过register作为起始点
public class MainController {
    @Autowired
    private UserRepository userRepository;

    @PostMapping(path ="/register")
    public @ResponseBody
    String addNewUser (@RequestParam String username , @RequestParam String password)
    {
        User n = new User();
        //检查合法性
        String regex1 = "^[1][3,4,5,7,8][0-9]{9}$";
        Pattern p = Pattern.compile(regex1);
        Matcher m = p.matcher(username);
        if(m.matches())
            n.setUsername(username);
        else
            return "用户名格式错误，请重新输入";
        String regex = "^([a-zA-Z0-9~`#$%^&*!@.,()\\\\{}|:;?<>]){8,12}$";
        boolean isRight = password.matches(regex);
        if(isRight)
            n.setPassword(getMD5(password));
        else
            return "密码格式错误，请重新输入";
        userRepository.save(n);
        return "注册成功";
    }
    @GetMapping(path="/all")
    public @ResponseBody Iterable<User> getAllUsers(){
        return  userRepository.findAll();
    }
}
